<template>
	<view class="container">
	<view class="header">
		<text class="title">{{ isAddMode ? '新增备件' : '编辑备件' }}</text>
		<view class="save-btn" @click="savePart">
			<text class="save-text">保存</text>
		</view>
	</view>

		<view class="content" v-if="form">
			<!-- 基本信息 -->
			<view class="section">
				<view class="section-title">基本信息</view>
				<view class="form-grid">
					<view class="field">
						<text class="label">备件编号</text>
						<input class="input" v-model="form.partNo" placeholder="请输入备件编号" />
					</view>
					<view class="field">
						<text class="label">备件名称</text>
						<input class="input" v-model="form.partName" placeholder="请输入备件名称" />
					</view>
					<view class="field">
						<text class="label">规格型号</text>
						<input class="input" v-model="form.specNo" placeholder="请输入规格型号" />
					</view>
					<view class="field">
						<text class="label">备件类型</text>
						<picker mode="selector" :range="typeList" range-key="name" @change="onTypeChange">
							<view class="input picker">{{ typeName || '请选择备件类型' }}</view>
						</picker>
					</view>
					<view class="field">
						<text class="label">仓库</text>
						<picker mode="selector" :range="warehouseList" range-key="name" @change="onWhChange">
							<view class="input picker">{{ warehouseName || '请选择仓库' }}</view>
						</picker>
					</view>
				</view>
			</view>

			<!-- 关联资产 -->
			<view class="section">
				<view class="section-title">关联资产</view>
				<view class="asset-list">
					<view class="asset-item" v-for="(asset, index) in form.relatedAssets" :key="index">
						<view class="asset-info">
							<text class="asset-name">{{ asset.assetName }}</text>
							<text class="asset-no">{{ asset.assetNo }}</text>
						</view>
						<text class="remove-btn" @tap="removeAsset(index)">×</text>
					</view>
					<view class="add-asset-btn" @tap="selectAssets">
						<text class="add-icon">+</text>
						<text class="add-text">快速选择</text>
					</view>
				</view>
			</view>

			<!-- 备件图片 -->
			<view class="section">
				<view class="section-title">备件图片</view>
				<view class="image-upload-tip">最多上传5张,单张不大于2MB。</view>
				<view class="image-list">
					<view class="image-item" v-for="(image, index) in previewImages" :key="index">
						<image :src="image" class="uploaded-image" mode="aspectFill"></image>
						<text class="remove-image" @tap="removeImage(index)">×</text>
					</view>
					<view class="upload-btn" @tap="chooseImage" v-if="form.images.length < 5">
						<text class="upload-icon">+</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 加载状态 -->
		<view class="loading" v-if="loading">
			<text class="loading-text">加载中...</text>
		</view>
	</view>
</template>

<script>
import { getPart, addPart, updatePart, uploadPartImage } from '@/api/inventory/part.js'
import { listWarehouseDTO } from '@/api/inventory/warehouse.js'
import { listPartType } from '@/api/dict/partType.js'

export default {
	data() {
		return {
			partNo: '',
			isAddMode: false, // 是否为新增模式
			loading: false,
			form: {
				partNo: '',
				partName: '',
				specNo: '',
				partTypeCode: '',
				warehouseCode: '',
				relatedAssets: [],
				images: []
			},
			typeList: [],
			warehouseList: [],
			typeName: '',
			warehouseName: '',
			// 备件类型映射
			typeMapping: {
				'BEARING': '轴承',
				'SEAL': '密封件',
				'FILTER': '过滤器',
				'BELT': '皮带',
				'CHAIN': '链条',
				'GEAR': '齿轮',
				'MOTOR': '电机',
				'PUMP': '泵',
				'VALVE': '阀门',
				'SENSOR': '传感器',
				'CONTROLLER': '控制器',
				'SWITCH': '开关',
				'CABLE': '电缆',
				'CONNECTOR': '连接器',
				'BOLT': '螺栓',
				'NUT': '螺母',
				'WASHER': '垫圈',
				'SPRING': '弹簧',
				'BUSHING': '衬套',
				'GASKET': '垫片'
			},
			// 仓库映射
			warehouseMapping: {
				'WH001': '主仓库',
				'WH002': '备用仓库',
				'WH003': '临时仓库',
				'MAIN': '主仓库',
				'BACKUP': '备用仓库',
				'TEMP': '临时仓库'
			}
		}
	},
	computed: {
		// 预览图片列表，构建完整的图片URL
		previewImages() {
			const minioBase = uni.getStorageSync('MINIO_BASE') || 'https://io.brightholdings.cn'
			const bucket = 'smart-maintenance'
			return (this.form.images || []).map(imageUrl => {
				if (!imageUrl) return '/static/banner-bg.jpg'
				if (/^https?:\/\//i.test(imageUrl)) return imageUrl
				// 使用MinIO方式构建图片URL
				return `${minioBase.replace(/\/$/, '')}/${bucket}/${imageUrl}`
			})
		}
	},
	onLoad(options) {
		if (options.partNo) {
			// 编辑模式
			this.isAddMode = false;
			this.partNo = options.partNo;
			this.loadData();
		} else {
			// 新增模式
			this.isAddMode = true;
			this.loading = false;
			this.loadMeta(); // 只加载元数据（类型和仓库列表）
		}
	},
	onShow() {
		// 处理从资产选择页面返回的数据
		const selectedAssets = uni.getStorageSync('selectedAssets')
		if (selectedAssets && selectedAssets.length > 0) {
			this.form.relatedAssets = [...this.form.relatedAssets, ...selectedAssets]
			uni.removeStorageSync('selectedAssets')
		}
	},
	methods: {
		async loadData() {
			try {
				this.loading = true
				await Promise.all([
					this.loadPartDetail(),
					this.loadMeta()
				])
			} catch (e) {
				console.error('加载数据失败:', e)
				uni.showToast({ title: '加载失败', icon: 'none' })
			} finally {
				this.loading = false
			}
		},

		async loadPartDetail() {
			try {
				const res = await getPart(this.partNo)
				console.log('备件详情API返回:', res)
				
				if (res && res.code === 200 && res.data) {
					const data = res.data
					
					// 处理图片数据
					let images = []
					if (data.imageUrls) {
						try {
							if (typeof data.imageUrls === 'string') {
								images = JSON.parse(data.imageUrls)
							} else if (Array.isArray(data.imageUrls)) {
								images = data.imageUrls
							}
						} catch (e) {
							console.error('解析图片数据失败:', e)
						}
					}
					
					// 处理关联资产数据
					let assets = []
					if (data.associatedAssetsJson) {
						try {
							if (typeof data.associatedAssetsJson === 'string') {
								assets = JSON.parse(data.associatedAssetsJson)
							} else if (Array.isArray(data.associatedAssetsJson)) {
								assets = data.associatedAssetsJson
							}
						} catch (e) {
							console.error('解析关联资产数据失败:', e)
						}
					}
					
					this.form = {
						partNo: data.partNo,
						partName: data.partName,
						specNo: data.specNo,
						partTypeCode: data.partTypeCode,
						warehouseCode: data.warehouseCode,
						relatedAssets: assets,
						images: images
					}
					
					// 设置显示名称
					this.typeName = this.typeMapping[data.partTypeCode] || data.partTypeCode
					this.warehouseName = this.warehouseMapping[data.warehouseCode] || data.warehouseCode
					
					console.log('加载的备件数据:', this.form)
				} else {
					uni.showToast({ title: res.msg || '获取备件详情失败', icon: 'none' })
				}
			} catch (e) {
				console.error('加载备件详情失败:', e)
				uni.showToast({ title: '加载失败', icon: 'none' })
			}
		},

		async loadMeta() {
			// 加载备件类型
			try {
				const r = await listPartType({})
				console.log('备件类型API返回:', r)
				
				if (r && r.code === 200 && r.rows && Array.isArray(r.rows)) {
					this.typeList = r.rows.map(d => ({
						code: d.code || d.id,
						name: d.name || d.label
					}))
					console.log('备件类型处理完成:', this.typeList)
				} else if (r && r.code === 200 && r.data && Array.isArray(r.data)) {
					this.typeList = r.data.map(d => ({
						code: d.code || d.id,
						name: d.name || d.label
					}))
					console.log('备件类型处理完成:', this.typeList)
				} else {
					console.log('备件类型数据为空或格式不正确')
					this.typeList = []
				}
			} catch (e) {
				console.error('加载备件类型失败:', e)
				this.typeList = []
			}

			// 加载仓库列表
			try {
				const r = await listWarehouseDTO({})
				console.log('仓库API返回:', r)

				if (r && r.code === 200 && r.data && Array.isArray(r.data)) {
					this.warehouseList = r.data.map(w => ({
						code: w.code || w.id || w.warehouseCode || '',
						name: w.name || w.warehouseName || w.label || w.text
					}))
					console.log('仓库列表处理完成:', this.warehouseList)
				} else {
					console.log('仓库数据为空或格式不正确')
					this.warehouseList = []
				}
			} catch (e) {
				console.error('加载仓库列表失败:', e)
				this.warehouseList = []
			}
		},

		onTypeChange(e) {
			const index = e.detail.value
			const selected = this.typeList[index]
			this.form.partTypeCode = selected.code
			this.typeName = selected.name
		},

		onWhChange(e) {
			const index = e.detail.value
			const selected = this.warehouseList[index]
			this.form.warehouseCode = selected.code
			this.warehouseName = selected.name
		},

		selectAssets() {
			uni.navigateTo({
				url: '/pages/asset/list?selectMode=true'
			})
		},

		removeAsset(index) {
			this.form.relatedAssets.splice(index, 1)
		},

		chooseImage() {
			uni.chooseImage({
				count: 5 - this.form.images.length,
				sizeType: ['compressed'],
				sourceType: ['album', 'camera'],
				success: (res) => {
					console.log('选择的图片:', res.tempFilePaths)
					this.uploadImages(res.tempFilePaths)
				},
				fail: (err) => {
					console.error('选择图片失败:', err)
					uni.showToast({ title: '选择图片失败', icon: 'none' })
				}
			})
		},

		async uploadImages(filePaths) {
			try {
				uni.showLoading({ title: '上传中...' })
				
				for (let i = 0; i < filePaths.length; i++) {
					const filePath = filePaths[i]
					console.log(`上传第${i+1}张图片:`, filePath)
					
					// 检查文件大小
					const fileInfo = await uni.getFileInfo({ filePath })
					if (fileInfo.size > 2 * 1024 * 1024) {
						uni.showToast({ title: `第${i+1}张图片超过2MB`, icon: 'none' })
						continue
					}
					
					const fileName = await uploadPartImage(filePath)
					console.log('上传成功，文件名:', fileName)
					
					// 直接存储文件名，让previewImages计算属性处理URL构建
					this.form.images.push(fileName)
					console.log('添加图片文件名:', fileName)
				}
				uni.hideLoading()
				uni.showToast({ title: '上传成功', icon: 'success' })
			} catch (e) {
				uni.hideLoading()
				console.error('上传图片失败:', e)
				uni.showToast({ title: '上传失败: ' + (e.message || '未知错误'), icon: 'none' })
			}
		},

		removeImage(index) {
			this.form.images.splice(index, 1)
		},

		async savePart() {
			try {
				// 验证必填字段
				if (this.isAddMode && !this.form.partNo) {
					uni.showToast({ title: '请输入备件编号', icon: 'none' })
					return
				}
				if (!this.form.partName) {
					uni.showToast({ title: '请输入备件名称', icon: 'none' })
					return
				}
				if (!this.form.specNo) {
					uni.showToast({ title: '请输入规格型号', icon: 'none' })
					return
				}
				if (!this.form.partTypeCode) {
					uni.showToast({ title: '请选择备件类型', icon: 'none' })
					return
				}
				if (!this.form.warehouseCode) {
					uni.showToast({ title: '请选择仓库', icon: 'none' })
					return
				}
				
				const payload = { 
					partNo: this.form.partNo,
					partName: this.form.partName,
					specNo: this.form.specNo,
					partTypeCode: this.form.partTypeCode,
					warehouseCode: this.form.warehouseCode,
					associatedAssetsJson: this.form.relatedAssets.length > 0 ? JSON.stringify(this.form.relatedAssets) : '',
					imageUrls: this.form.images.length > 0 ? JSON.stringify(this.form.images) : ''
				}
				
				// 编辑时需要oldPartNo
				if (!this.isAddMode) {
					payload.oldPartNo = this.form.partNo;
				}
				
				console.log(this.isAddMode ? '新增数据:' : '更新数据:', payload)
				
				uni.showLoading({ title: '保存中...' })
				
				// 根据模式调用不同的API
				const r = this.isAddMode ? await addPart(payload) : await updatePart(payload);
				
				uni.hideLoading()
				
				if (r && r.code === 200) {
					uni.showToast({ title: '保存成功', icon: 'success' })
					// 设置标记，通知台账页面需要刷新
					uni.setStorageSync('needRefreshLedger', true)
					setTimeout(() => uni.navigateBack(), 1500)
				} else {
					uni.showToast({ title: r.msg || '保存失败', icon: 'none' })
				}
			} catch (e) {
				uni.hideLoading()
				console.error('保存失败:', e)
				uni.showToast({ title: '保存失败: ' + (e.message || '未知错误'), icon: 'none' })
			}
		},

		goBack() {
			uni.navigateBack()
		}
	}
}
</script>

<style scoped>
.container {
	min-height: 100vh;
	background-color: #f5f6f7;
}

.header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 30rpx;
	background: #fff;
	border-bottom: 1rpx solid #eee;
}

.save-btn {
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.title {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
}

.save-text {
	font-size: 28rpx;
	color: #4a94ff;
	font-weight: 500;
}

.content {
	padding: 20rpx;
}

.section {
	background: #fff;
	border-radius: 16rpx;
	margin-bottom: 20rpx;
	overflow: hidden;
}

.section-title {
	font-size: 28rpx;
	font-weight: 600;
	color: #333;
	padding: 30rpx 30rpx 20rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.form-grid {
	padding: 20rpx 30rpx 30rpx;
}

.field {
	margin-bottom: 30rpx;
}

.field:last-child {
	margin-bottom: 0;
}

.label {
	font-size: 28rpx;
	color: #333;
	font-weight: 500;
	display: block;
	margin-bottom: 15rpx;
}

.input {
	width: 100%;
	height: 80rpx;
	background: #f8f9fa;
	border: 1rpx solid #e9ecef;
	border-radius: 12rpx;
	padding: 0 20rpx;
	font-size: 28rpx;
	color: #333;
	box-sizing: border-box;
}

.input.picker {
	display: flex;
	align-items: center;
	color: #666;
}

.input:disabled {
	background: #f5f5f5;
	color: #999;
}

.asset-list {
	padding: 20rpx 30rpx 30rpx;
}

.asset-item {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #f8f8f8;
}

.asset-item:last-child {
	border-bottom: none;
}

.asset-info {
	flex: 1;
}

.asset-name {
	font-size: 28rpx;
	color: #333;
	font-weight: 500;
	display: block;
	margin-bottom: 8rpx;
}

.asset-no {
	font-size: 24rpx;
	color: #666;
	display: block;
}

.remove-btn {
	width: 40rpx;
	height: 40rpx;
	background: #ff4757;
	color: #fff;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 24rpx;
}

.add-asset-btn {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 30rpx;
	border: 2rpx dashed #ddd;
	border-radius: 12rpx;
	margin-top: 20rpx;
}

.add-icon {
	font-size: 32rpx;
	color: #4a94ff;
	margin-right: 10rpx;
}

.add-text {
	font-size: 28rpx;
	color: #4a94ff;
}

.image-upload-tip {
	font-size: 24rpx;
	color: #999;
	padding: 0 30rpx 20rpx;
}

.image-list {
	padding: 0 30rpx 30rpx;
	display: flex;
	flex-wrap: wrap;
	gap: 20rpx;
}

.image-item {
	position: relative;
	width: 200rpx;
	height: 200rpx;
	border-radius: 12rpx;
	overflow: hidden;
}

.uploaded-image {
	width: 100%;
	height: 100%;
}

.remove-image {
	position: absolute;
	top: 10rpx;
	right: 10rpx;
	width: 40rpx;
	height: 40rpx;
	background: rgba(0, 0, 0, 0.6);
	color: #fff;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 24rpx;
}

.upload-btn {
	width: 200rpx;
	height: 200rpx;
	border: 2rpx dashed #ddd;
	border-radius: 12rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.upload-icon {
	font-size: 60rpx;
	color: #ccc;
}

.loading {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 100rpx 0;
}

.loading-text {
	font-size: 28rpx;
	color: #999;
}
</style>
